package com.asfo.demo.controller;

import com.asfo.demo.comm.ResultObject;
import com.asfo.demo.service.IFlowService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工申请假
 * 经理审批假
 * 结束
 */
@RequestMapping("/flow")
@Controller
public class FlowController {

    @Autowired
    private IFlowService flowService;

    /**
     * 创建流程引擎
     * @return
     */
    @RequestMapping("/createFlow")
    @ResponseBody
    public Object createFlow(@RequestBody  Map<String,Object> paras){
        String flowName = (String) paras.get("flowName");
        if(StringUtils.isEmpty(flowName)){
            return ResultObject.buildFail();
        }

        HashMap<Object, Object> resultMap = new HashMap<>();

        Deployment flow = flowService.createFlow(flowName);
        return flow!=null? ResultObject.buildSuccess():ResultObject.buildFail();
    }

    /**
     * 员工申请
     * @return
     */
    @RequestMapping(value = "/startApply",method = {RequestMethod.POST })
    @ResponseBody
    public Object startApply(@RequestBody  Map<String,Object> paras){
        String processKey = (String) paras.get("processKey");
        if(StringUtils.isEmpty(processKey)){
            return ResultObject.buildFail("processKey 为空");
        }
        Map<String, Object> inParams=new HashMap<>();
        inParams.putAll(paras);
        ProcessInstance processInstance = flowService.startFlow(processKey, inParams);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("processId",processInstance.getProcessInstanceId());
        return ResultObject.buildSuccess(resultMap);
    }



    /**
     * 员工查看流程
     * @return
     * @param response
     * @param processId
     */
    @RequestMapping(value = "/viewFlow",method = RequestMethod.GET)
    public void viewFlow(HttpServletResponse response, String processId){
        flowService.genProcessDiagram(response,processId);
    }

    /**
     * 完成流程
     * @return
     */
    @RequestMapping("/completeFlow")
    @ResponseBody
    public Object completeFlow(@RequestBody  Map<String,Object> paras){
        if(!paras.containsKey("taskId"))return ResultObject.buildFail("taskId 不为空");
        String taskId = (String) paras.get("taskId");
        paras.remove("taskId");
        boolean b = flowService.completeFlow(taskId, paras);
        return  b?ResultObject.buildSuccess():ResultObject.buildFail();
    }




}
